package cn.edu.mju.property.web.controller;

import cn.edu.mju.property.dao.UserDao;
import cn.edu.mju.property.dao.impl.UserDaoImpl;
import cn.edu.mju.property.entity.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {

        //1.设置编码
        request.setCharacterEncoding("utf-8");

        Map<String,String[]> map = request.getParameterMap();
        User loginUser = new User();
        //使用BeanUtils封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserDao dao = new UserDaoImpl();
        User user = dao.longin(loginUser);

        if(user==null){
            //登录失败
            //request.getRequestDispatcher()
            response.getWriter().write("loginError");
        }else {
            //登录成功
            request.getSession().setAttribute("user",user);
            response.getWriter().write("loginSuccess");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
